function createUniqueString() {
	  const timestamp = +new Date() + ''
	  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
	  return (+(randomNum + timestamp)).toString(32)
	}
function uniqueArr(arr) {
	  return Array.from(new Set(arr))
	}
function diffArary(arr1, arr2) {
	  arr1 = uniqueArr(arr1)
	  arr2 = uniqueArr(arr2)
	  return arr1.concat(arr2).filter(arg => !(arr1.includes(arg)  && arr2.includes(arg)))
	}
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

$(function () {
	var app = new Vue({
		el:'#app',
		data:{
			isCollapse: true,
			labelPosition:'left',
			queryIng : false, //正在查询
			queryData:{activeFlag:'1',page:1,rows:10}, //查询条件
			datagrid:[], //数据列表数据
			totalNum:0, //分页控件配置
			data:[],
			defaultCheckedKeys:[],
			addData:{
				classifyName:null,
				classifyCode:null
			},
			selectedRow:null,
			isEdit:false,
			rules:{
				name: [{ required: true, message: '该项必填', trigger: 'change' }],
				classifyName: [{ required: true, message: '该项必填', trigger: 'change' }],
				publishStatus: [{ required: true, message: '该项必填', trigger: 'change' }],
				guidePrice: [{ required: true, message: '该项必填', trigger: 'change' }],
				sellPrice: [{ required: true, message: '该项必填', trigger: 'change' }],
				imgList: [{ required: true, message: '该项必填', trigger: 'change' }],
			},
			dialogConfig:{
				formLabelWidth:'120px'
				,dialogFormVisible:false
			},
			size:"mini",
			addValues: [],
			specification:[],
			cascaderOptions:[],
			cascaderProps:{
				value:"id",
				label:"itemName"
			},
			imageUrl_goodsImage:null,
			imgArray:[],
			shopId:$("#shopId").val(),
			shopName:$("#shopName").val(),
			freightOptions:[]
		},
		components:{
			'skutable': skutableJs,
			'skuselect':skuSelectJs
		},
		methods: {
			init:function () {
				var vm = this
				vm.query();
				this.queryClassify();
				this.queryFreight();
			},
			search:function(){
				//点击查询按钮，默认查询第一页。
				this.queryData.page=1;
				this.query();
			},
			queryFreight:function(){
				var that = this;
				$.ajax({
					url :staticURL+'/mall/freight/listAll',
					data : {
						shopId:that.shopId,
						activeFlag:"1"
					},
					dataType : 'json',
					success : function(r) {
						that.freightOptions = r.data;
					}
				});
			},
			handleFreight:function(id){
				var that = this;
				for(var i=0;i< that.freightOptions.length;i++){
					if(that.freightOptions[i].id == id){
						that.addData.freightName = that.freightOptions[i].name;
					}
				}
			},
			query:function () {
				var vm = this
				if(vm.queryIng){
					return;
				}
				vm.queryIng = true;
				vm.queryData.shopId=vm.shopId;
				$.ajax({
					url :staticURL+'/mall/goods/datagrid',
					data : vm.queryData,
					dataType : 'json',
					success : function(json) {
						app.datagrid = json.rows;
						app.totalNum = json.total;
						app.queryIng = false;
						app.selectedRow = null;
					}
				});
			},
			queryClassify:function(){
				$.ajax({
					url :staticURL+'/mall/classify/listAll2',
					data : {
						queryLevel:0,
						activeFlag:1,
						rows:9999
					},
					dataType : 'json',
					success : function(json) {
						app.cascaderOptions = json.data;
					}
				});
			},
			handleClassify:function(v){
				var that = this;
				var parentId = v[0];
				var id = v[1];
				var id2 = v[2];
				for(var i=0;i<that.cascaderOptions.length;i++){
					if(parentId==that.cascaderOptions[i].id){
						for(var j=0;j<that.cascaderOptions[i].children.length;j++){
							if(id==that.cascaderOptions[i].children[j].id){
								for(var k=0;k<that.cascaderOptions[i].children[j].children.length;k++){
									if(id2==that.cascaderOptions[i].children[j].children[k].id){
										that.addData.classifyName = that.cascaderOptions[i].children[j].children[k].itemName;
										that.addData.classifyCode = that.cascaderOptions[i].children[j].children[k].id;
										break;
									}
								}
								break;
							}
						}
						break;
					}
				}
			},
			addItem:function(){
				app.openDialog();
			},
			deleteItem:function(row){
				app.$confirm('是否确认删除操作?', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			        }).then(function () {
			        	$.ajax({
			        		url : staticURL+"/mall/goods/delete?ids="+row.id,
							dataType : 'json',
							success : function(r) {
								if (r.success) {
									app.$notify({showClose: true,
								          message: r.msg,
								          type: 'success',
								          position: 'bottom-right'});
									app.query();
								} else {
									app.$notify({showClose: true,
								          message: r.msg,
								          type: 'error',
								          position: 'bottom-right'});
								}
							}
						});
			        }).catch(function (action) {
			        	  //取消
			        });
				return;
				
			},
			editItem:function(row){
				app.openDialog(row);
			},
			handleSizeChange:function(val){
				app.queryData.rows=val;
				app.query();
			},
			handleCurrentChange:function(val){
				app.queryData.page=val;
				app.query();
			},
			handlePrevClick:function(val){
				app.queryData.page=val;
				app.query();
			},
			handleNextClick:function(val){
				app.queryData.page=val;
				app.query();
			},
			handleTreeCheckChange:function(data){
				app.queryData.parentCode = data.id;
				app.query();
			},
			resetForm:function(formName) {
				app.$refs[formName].resetFields();
		    },
			submitForm:function(formName){
				var imgAry = []
				for(var i=0;i<app.imgArray.length;i++){
					imgAry.push(app.imgArray[i].url);
				}
				app.addData.imgList = imgAry.join(",");
				app.$refs[formName].validate(function(res){
					if(res){
						//app.addData.imgList = app.imgArray.join(",");
						/*console.log("app.addData.skuList",app.addData.skuList);
						return;*/
						app.addData.goodsDesc=UE.getEditor('add_editor').getContent();//设置富文本内容
						app.addData.attrList=app.specificationFilter;
						app.addData.skuList=app.$refs["skutable"].getData();
						if(!app.addData.attrList || app.addData.attrList.length==0){
							app.$notify({showClose: true,
						          message:"请录入商品规格",
						          type: 'error',
						          position: 'bottom-right'});
							return;
						}
						if(!app.addData.skuList || app.addData.skuList.length==0){
							app.$notify({showClose: true,
						          message:"请录入商品属性",
						          type: 'error',
						          position: 'bottom-right'});
							return;
						}
						//验证通过
						$.ajax({
							url : app.saveUrl,
							data : app.addData,
							data : JSON.stringify(app.addData),
							dataType : 'json',
							contentType:"application/json",
							success : function(r) {
								if (r.success) {
									app.dialogConfig.dialogFormVisible=false;
									app.$notify({showClose: true,
								          message: r.msg,
								          type: 'success',
								          position: 'bottom-right'});
									app.query();
								} else {
									app.$notify({showClose: true,
								          message: r.msg,
								          type: 'error',
								          position: 'bottom-right'});
								}
							}
						});
					}
				});
			},
			openDialog:function(param){
				if(param){
					app.isEdit = true;
					//这里如下操作，而不是 app.addData = param,是为了实现JSON对象的复制
					//如果app.addData = param， 当closeDialog()时，dialogForm 被reset
					//app.addDatat同时被reset,会导致bug
					app.addData = JSON.parse(JSON.stringify(param)); 
					app.specification = app.addData.attrList;
					app.imgArray=[];
					if(app.addData.imgList){
						var array = app.addData.imgList.split(",");
						for(var i=0;i<array.length;i++){
							app.imgArray.push({
								name:"1.jpg",
								url:array[i]
							});
						}
					}
				}else{
					app.isEdit = false;
					app.addData = {
							orderNum:1,
							shopId:this.shopId,
							shopName:this.shopName,
							publishStatus:"1",
							classifyName:null,
							classifyCode:null
							};
					app.specification=[];
					app.imgArray=[];
				}
				//显示dialog
				app.dialogConfig.dialogFormVisible=true;
				//重置form
				if(app.$refs['dialogForm']){
					app.$refs['dialogForm'].resetFields();
				}
				//设置富文本编辑器
				app.$nextTick(function(){
					UE.getEditor('add_editor');    //添加编辑器
					//加载数据
					UE.getEditor('add_editor').addListener("ready", function () {
						if(app.addData.goodsDesc){
							// editor准备好之后才可以使用
							UE.getEditor('add_editor').setContent(app.addData.goodsDesc);
						}
						app.editorReady = true;
					});
					if(app.editorReady && app.addData.goodsDesc){
						// editor准备好之后才可以使用
						UE.getEditor('add_editor').setContent(app.addData.goodsDesc);
					}else if(app.editorReady){
						UE.getEditor('add_editor').setContent("");
					}
					app.$refs["skutable"].setData(app.addData.skuList);
				})
			},
			closeDialog:function(){
				app.dialogConfig.dialogFormVisible=false;
				app.resetForm('dialogForm')
			},
			datagridSelect:function(row, event, column){
				app.selectedRow = row;
			},
			addSpec: function addSpec() {
				this.specification.push({
					id: createUniqueString() + '_id',
					value: '',
					leaf: []
				});
			},
			delSepc: function delSepc(index) {
				this.specification.splice(index, 1);
			},
			addOption: function addOption(index) {
				var str = this.addValues[index] || '';
				str = str.trim();
				if (!str) return;
				var oldArr = this.specification[index].leaf;
				var arr = str.split(/\s+/) // 使用空格分割成数组
					.filter(function(value) {
						return !oldArr.some(function(option) {
							return option.value === value;
						});
					}) // 过滤掉 oldArr 已存在的 value
					.map(function(value) {
						return {
							id: createUniqueString() + '_id',
							value: value
						};
					}); // 把 value 转成对象，id 设置为 null

				this.specification[index].leaf = uniqueArr([].concat(_toConsumableArray(oldArr), _toConsumableArray(arr)));
				this.$set(this.addValues, index, '');
			},
			delOption: function delOption(spec_index, option_index) {
				this.specification[spec_index].leaf.splice(option_index, 1);
			},
			handleAvatarSuccess_memberHeadImage:function(res, file) {
				console.log("handleAvatarSuccess_memberHeadImage ",res, file);
				app.imgArray.push({
					name:"1.jpg",
					url:res.imageUrl
				});
		    },
		    uploadUrl:function(){
				return staticURL+"/app/mytools/upload";
			},
		    beforeAvatarUpload:function(file) {

		        const isLt2M = file.size / 1024 / 1024 < 2;
	
		        if (!isLt2M) {
		          this.$message.error('上传图片大小不能超过 2MB!');
		        }
		        
		        return isLt2M;
		    },
		    handleRemove(file, fileList) {
		    	app.imgArray = fileList;
		    },
		},
		computed:{
			saveUrl:function(){
				if(app.isEdit){
					return staticURL+'/mall/goods/edit'
				}else{
					return staticURL+'/mall/goods/add'
				}
			},
			columnWidth:function(){

				let w = $(window).width();   

				w = w - 48-48-50-150;
				
				return Math.floor(w/5);
			},
			disabled: function disabled() {
				return this.specification.length >= 2 || this.specification.some(function(item) {
					return !item.value;
				});
			},
			// 过滤掉属性名和属性值为空的数据规格项目
			specificationFilter: function specificationFilter() {
				return this.specification.filter(function(item) {
					return item.value && item.leaf.length;
				});
			}
		},
		created: function () {
			if(!this.shopId){
				this.$alert('您还不是店主！', '',{
					showClose:false,
					showConfirmButton:false
				} );
			}else{
				this.init();
			}
		},
		updated:function(){
		}
	});
});